<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modern SSH Client</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#00B42A',
                        danger: '#F53F3F',
                        warning: '#FF7D00',
                        info: '#86909C',
                        dark: '#1D2129',
                        light: '#F2F3F5',
                        terminal: {
                            bg: '#000000',
                            text: '#FFFFFF',
                            cursor: '#00FF00'
                        }
                    },
                    fontFamily: {
                        mono: ['Consolas', 'Monaco', 'Courier New', 'monospace'],
                        inter: ['Inter', 'sans-serif']
                    },
                    boxShadow: {
                        'terminal': '0 0 15px rgba(0, 255, 0, 0.3)',
                        'tab': '0 2px 4px rgba(0, 0, 0, 0.1)'
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .terminal-cursor {
                animation: blink 1s step-end infinite;
            }
            .tab-transition {
                transition: all 0.3s ease;
            }
            .keyword-blue {
                color: #165DFF;
            }
            .keyword-green {
                color: #00B42A;
            }
            .keyword-yellow {
                color: #FF7D00;
            }
            .keyword-red {
                color: #F53F3F;
            }
            .keyword-purple {
                color: #722ED1;
            }
            .keyword-cyan {
                color: #0FC6C2;
            }
        }

        @keyframes blink {
            from, to { opacity: 1; }
            50% { opacity: 0; }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen font-inter text-dark">
    <div class="max-w-7xl mx-auto px-4 py-6">
        <!-- Header -->
        <header class="mb-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <i class="fa fa-terminal text-primary text-2xl"></i>
                    <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark">SSH Client</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="importBtn" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg flex items-center transition-all duration-300 hover:shadow-lg">
                        <i class="fa fa-download mr-2"></i> Import
                    </button>
                    <button id="exportBtn" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg flex items-center transition-all duration-300 hover:shadow-lg">
                        <i class="fa fa-upload mr-2"></i> Export
                    </button>
                </div>
            </div>
        </header>

        <!-- Connection Form -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6 transform transition-all duration-300 hover:shadow-xl">
            <h2 class="text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-plug text-primary mr-2"></i> Connect to Server
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label for="host" class="block text-sm font-medium text-gray-700 mb-1">Host</label>
                    <input type="text" id="host" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all" placeholder="192.168.1.1">
                </div>
                <div>
                    <label for="port" class="block text-sm font-medium text-gray-700 mb-1">Port</label>
                    <input type="number" id="port" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all" placeholder="22" value="22">
                </div>
                <div>
                    <label for="tabName" class="block text-sm font-medium text-gray-700 mb-1">Tab Name</label>
                    <input type="text" id="tabName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all" placeholder="Server">
                </div>
            </div>
            <div class="mt-4 flex justify-end">
                <button id="connectBtn" class="px-6 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg flex items-center transition-all duration-300 hover:shadow-lg">
                    <i class="fa fa-link mr-2"></i> Connect
                </button>
            </div>
        </div>

        <!-- Tabs Container -->
        <div class="bg-white rounded-t-xl shadow-lg overflow-hidden">
            <div id="tabs" class="flex border-b border-gray-200 overflow-x-auto scrollbar-hide">
                <!-- Tabs will be inserted here -->
            </div>
            
            <!-- Terminal Container -->
            <div id="terminal-container" class="bg-terminal-bg text-terminal-text font-mono min-h-[500px] p-4 overflow-auto relative">
                <div id="terminal-output" class="mb-2"></div>
                <div id="prompt" class="flex items-center">
                    <span id="user-host" class="text-secondary">user@server</span>
                    <span class="mx-1">:</span>
                    <span id="current-path" class="text-primary">~</span>
                    <span class="mx-1">$</span>
                    <span class="ml-1"></span>
                    <span id="cursor" class="terminal-cursor inline-block h-4 w-2 bg-terminal-cursor align-text-bottom"></span>
                </div>
                <input type="text" id="command-input" class="bg-transparent border-none outline-none text-terminal-text font-mono w-[calc(100%-120px)] ml-1" placeholder="Type command...">
            </div>
        </div>
    </div>

    <script>
        // Initialize tabs and commands history
        let tabs = [];
        let currentTabIndex = -1;
        let commandsHistory = [];
        let historyPosition = 0;

        // Keywords for syntax highlighting
        const keywords = {
            commands: ['ls', 'cd', 'mkdir', 'rm', 'rmdir', 'cp', 'mv', 'touch', 'cat', 'grep', 'ssh', 'scp', 'sudo', 'su', 'exit', 'clear', 'pwd', 'echo', 'man', 'help'],
            options: ['-a', '-l', '-h', '-r', '-f', '-v', '--help', '--version'],
            variables: ['$HOME', '$PATH', '$USER', '$PWD'],
            system: ['root', 'localhost', 'etc', 'var', 'bin', 'sbin', 'usr', 'home', 'dev']
        };

        // DOM Elements
        const tabsContainer = document.getElementById('tabs');
        const terminalOutput = document.getElementById('terminal-output');
        const commandInput = document.getElementById('command-input');
        const userHostSpan = document.getElementById('user-host');
        const currentPathSpan = document.getElementById('current-path');
        const connectBtn = document.getElementById('connectBtn');
        const importBtn = document.getElementById('importBtn');
        const exportBtn = document.getElementById('exportBtn');

        // Initialize from cookies
        function initializeFromCookies() {
            const savedTabs = getCookie('sshClientTabs');
            if (savedTabs) {
                try {
                    tabs = JSON.parse(savedTabs);
                    renderTabs();
                    if (tabs.length > 0) {
                        switchTab(0);
                    }
                } catch (e) {
                    console.error('Failed to parse saved tabs:', e);
                    tabs = [];
                }
            }
        }

        // Cookie functions
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }

        function setCookie(name, value, days = 365) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
        }

        // Tab functions
        function addTab(host, port, tabName) {
            const newTab = {
                id: Date.now().toString(),
                host,
                port,
                name: tabName || host,
                history: [],
                user: 'user',
                hostDisplay: 'server',
                path: '~'
            };
            
            tabs.push(newTab);
            renderTabs();
            setCookie('sshClientTabs', JSON.stringify(tabs));
            switchTab(tabs.length - 1);
        }

        function renderTabs() {
            tabsContainer.innerHTML = '';
            tabs.forEach((tab, index) => {
                const tabElement = document.createElement('div');
                tabElement.className = `tab-transition px-4 py-3 cursor-pointer ${index === currentTabIndex ? 'border-b-2 border-primary text-primary font-medium' : 'text-gray-600 hover:bg-gray-50'}`;
                tabElement.innerHTML = `
                    <div class="flex items-center">
                        <span>${tab.name}</span>
                        <button class="ml-2 text-gray-400 hover:text-danger tab-transition opacity-0 group-hover:opacity-100">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                `;
                
                tabElement.addEventListener('click', () => switchTab(index));
                
                const closeBtn = tabElement.querySelector('button');
                closeBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    removeTab(index);
                });
                
                tabElement.addEventListener('dblclick', (e) => {
                    e.stopPropagation();
                    renameTab(index);
                });
                
                tabsContainer.appendChild(tabElement);
            });
            
            // Add new tab button
            const newTabButton = document.createElement('div');
            newTabButton.className = 'px-4 py-3 cursor-pointer text-gray-500 hover:text-primary hover:bg-gray-50 tab-transition';
            newTabButton.innerHTML = '<i class="fa fa-plus"></i>';
            newTabButton.addEventListener('click', () => {
                document.getElementById('host').focus();
            });
            tabsContainer.appendChild(newTabButton);
        }

        function switchTab(index) {
            if (index >= 0 && index < tabs.length) {
                currentTabIndex = index;
                renderTabs();
                updateTerminalUI();
                renderTerminalOutput();
                commandsHistory = tabs[index].history || [];
                historyPosition = commandsHistory.length;
                commandInput.value = '';
                commandInput.focus();
            }
        }

        function removeTab(index) {
            if (tabs.length > 1) {
                tabs.splice(index, 1);
                setCookie('sshClientTabs', JSON.stringify(tabs));
                renderTabs();
                
                if (currentTabIndex >= tabs.length) {
                    switchTab(tabs.length - 1);
                } else {
                    switchTab(currentTabIndex);
                }
            }
        }

        function renameTab(index) {
            const newName = prompt('Enter new tab name:', tabs[index].name);
            if (newName && newName.trim() !== '') {
                tabs[index].name = newName.trim();
                setCookie('sshClientTabs', JSON.stringify(tabs));
                renderTabs();
            }
        }

        function updateTerminalUI() {
            if (currentTabIndex >= 0) {
                const currentTab = tabs[currentTabIndex];
                userHostSpan.textContent = `${currentTab.user}@${currentTab.hostDisplay}`;
                currentPathSpan.textContent = currentTab.path;
            }
        }

        // Terminal functions
        function renderTerminalOutput() {
            terminalOutput.innerHTML = '';
            if (currentTabIndex >= 0) {
                const currentTab = tabs[currentTabIndex];
                currentTab.history.forEach(item => {
                    if (item.type === 'command') {
                        appendCommandToOutput(item.command);
                    } else if (item.type === 'output') {
                        appendOutput(item.content);
                    } else if (item.type === 'error') {
                        appendError(item.content);
                    } else if (item.type === 'connection') {
                        appendConnectionMessage(item.content);
                    }
                });
            }
        }

        function appendCommandToOutput(command) {
            const commandLine = document.createElement('div');
            commandLine.className = 'mb-1';
            commandLine.innerHTML = `
                <span class="text-secondary">${tabs[currentTabIndex].user}@${tabs[currentTabIndex].hostDisplay}</span>
                <span class="mx-1">:</span>
                <span class="text-primary">${tabs[currentTabIndex].path}</span>
                <span class="mx-1">$</span>
                <span class="ml-1">${highlightSyntax(command)}</span>
            `;
            terminalOutput.appendChild(commandLine);
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
        }

        function appendOutput(content) {
            const outputLine = document.createElement('div');
            outputLine.className = 'mb-1 text-gray-300';
            outputLine.innerHTML = highlightSyntax(content);
            terminalOutput.appendChild(outputLine);
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
        }

        function appendError(content) {
            const errorLine = document.createElement('div');
            errorLine.className = 'mb-1 text-danger';
            errorLine.innerHTML = highlightSyntax(content);
            terminalOutput.appendChild(errorLine);
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
        }

        function appendConnectionMessage(content) {
            const connLine = document.createElement('div');
            connLine.className = 'mb-1 text-warning';
            connLine.innerHTML = highlightSyntax(content);
            terminalOutput.appendChild(connLine);
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
        }

        function highlightSyntax(text) {
            if (!text) return '';
            
            // Escape HTML
            let result = text.replace(/[&<>"']/g, char => {
                const entities = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#39;'
                };
                return entities[char] || char;
            });
            
            // Highlight commands
            keywords.commands.forEach(cmd => {
                const regex = new RegExp(`\\b${cmd}\\b`, 'g');
                result = result.replace(regex, `<span class="keyword-blue">${cmd}</span>`);
            });
            
            // Highlight options
            keywords.options.forEach(opt => {
                const regex = new RegExp(`\\s(${opt})\\b`, 'g');
                result = result.replace(regex, ` <span class="keyword-green">${opt}</span>`);
            });
            
            // Highlight variables
            keywords.variables.forEach(varName => {
                const regex = new RegExp(`\\b${varName}\\b`, 'g');
                result = result.replace(regex, `<span class="keyword-purple">${varName}</span>`);
            });
            
            // Highlight system words
            keywords.system.forEach(word => {
                const regex = new RegExp(`\\b${word}\\b`, 'g');
                result = result.replace(regex, `<span class="keyword-cyan">${word}</span>`);
            });
            
            // Highlight strings
            result = result.replace(/"([^"]*)"/g, `<span class="keyword-yellow">"$1"</span>`);
            result = result.replace(/'([^']*)'/g, `<span class="keyword-yellow">'$1'</span>`);
            
            return result;
        }

        function executeCommand(command) {
            if (!command.trim()) return;
            
            // Add command to history
            if (currentTabIndex >= 0) {
                const currentTab = tabs[currentTabIndex];
                currentTab.history.push({ type: 'command', command });
                
                // Process command
                if (command === 'clear') {
                    currentTab.history = [];
                } else if (command === 'exit') {
                    if (tabs.length > 1) {
                        removeTab(currentTabIndex);
                    } else {
                        appendOutput('Cannot exit the last tab');
                    }
                    return;
                } else if (command.startsWith('cd ')) {
                    const dir = command.substring(3).trim();
                    if (dir === '..') {
                        // Simplified directory navigation
                        const parts = currentTab.path.split('/');
                        if (parts.length > 1) {
                            parts.pop();
                            currentTab.path = parts.join('/') || '~';
                        }
                    } else if (dir === '') {
                        currentTab.path = '~';
                    } else {
                        currentTab.path = currentTab.path === '~' ? dir : `${currentTab.path}/${dir}`;
                    }
                    updateTerminalUI();
                } else if (command === 'ls') {
                    appendOutput('drwxr-xr-x  2 user group 4096 Jun 25 10:00 Documents\n' +
                                'drwxr-xr-x  2 user group 4096 Jun 25 10:00 Downloads\n' +
                                '-rw-r--r--  1 user group  123 Jun 25 10:00 file.txt\n' +
                                'drwxr-xr-x  2 user group 4096 Jun 25 10:00 Pictures\n' +
                                'drwxr-xr-x  2 user group 4096 Jun 25 10:00 Videos');
                } else if (command === 'pwd') {
                    appendOutput(currentTab.path === '~' ? '/home/user' : `/home/user/${currentTab.path}`);
                } else if (command === 'help') {
                    appendOutput('Available commands:\n' +
                                '  ls         - List directory contents\n' +
                                '  cd [dir]   - Change directory\n' +
                                '  pwd        - Print working directory\n' +
                                '  clear      - Clear terminal screen\n' +
                                '  exit       - Close current tab\n' +
                                '  help       - Show this help message');
                } else {
                    appendError(`Command not found: ${command}`);
                }
                
                // Save updated history
                setCookie('sshClientTabs', JSON.stringify(tabs));
            }
        }

        // Import/Export functions
        function exportConfig() {
            const xmlDoc = document.implementation.createDocument(null, "sshConfig");
            const tabsElement = xmlDoc.createElement("tabs");
            
            tabs.forEach(tab => {
                const tabElement = xmlDoc.createElement("tab");
                
                const idElement = xmlDoc.createElement("id");
                idElement.textContent = tab.id;
                tabElement.appendChild(idElement);
                
                const nameElement = xmlDoc.createElement("name");
                nameElement.textContent = tab.name;
                tabElement.appendChild(nameElement);
                
                const hostElement = xmlDoc.createElement("host");
                hostElement.textContent = tab.host;
                tabElement.appendChild(hostElement);
                
                const portElement = xmlDoc.createElement("port");
                portElement.textContent = tab.port;
                tabElement.appendChild(portElement);
                
                tabsElement.appendChild(tabElement);
            });
            
            xmlDoc.documentElement.appendChild(tabsElement);
            
            const serializer = new XMLSerializer();
            const xmlString = serializer.serializeToString(xmlDoc);
            
            const blob = new Blob([xmlString], {type: "text/xml"});
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement("a");
            a.href = url;
            a.download = "ssh_config.xml";
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function importConfig() {
            const input = document.createElement("input");
            input.type = "file";
            input.accept = ".xml";
            
            input.onchange = (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        try {
                            const xmlDoc = new DOMParser().parseFromString(event.target.result, "text/xml");
                            const tabElements = xmlDoc.querySelectorAll("tab");
                            
                            const importedTabs = Array.from(tabElements).map(tabEl => {
                                return {
                                    id: tabEl.querySelector("id").textContent,
                                    name: tabEl.querySelector("name").textContent,
                                    host: tabEl.querySelector("host").textContent,
                                    port: parseInt(tabEl.querySelector("port").textContent) || 22,
                                    history: [],
                                    user: 'user',
                                    hostDisplay: 'server',
                                    path: '~'
                                };
                            });
                            
                            if (importedTabs.length > 0) {
                                tabs = [...importedTabs];
                                setCookie('sshClientTabs', JSON.stringify(tabs));
                                renderTabs();
                                if (tabs.length > 0) {
                                    switchTab(0);
                                }
                                appendConnectionMessage(`Imported ${importedTabs.length} connection profiles`);
                            } else {
                                appendError("No connection profiles found in the XML file");
                            }
                        } catch (error) {
                            appendError("Failed to parse XML file: " + error.message);
                        }
                    };
                    reader.readAsText(file);
                }
            };
            
            document.body.appendChild(input);
            input.click();
            document.body.removeChild(input);
        }

        // Event listeners
        connectBtn.addEventListener('click', () => {
            const host = document.getElementById('host').value.trim();
            const port = parseInt(document.getElementById('port').value) || 22;
            const tabName = document.getElementById('tabName').value.trim();
            
            if (!host) {
                alert('Please enter a host');
                return;
            }
            
            addTab(host, port, tabName);
            
            // Clear form
            document.getElementById('host').value = '';
            document.getElementById('port').value = 22;
            document.getElementById('tabName').value = '';
            
            // Simulate connection
            if (currentTabIndex >= 0) {
                const currentTab = tabs[currentTabIndex];
                currentTab.history.push({ 
                    type: 'connection', 
                    content: `Connecting to ${host}:${port}...\n` +
                            `Welcome to ${host} (Linux)\n` +
                            `Last login: ${new Date().toLocaleString()}\n`
                });
                setCookie('sshClientTabs', JSON.stringify(tabs));
                renderTerminalOutput();
            }
        });

        commandInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                const command = commandInput.value.trim();
                executeCommand(command);
                commandInput.value = '';
                historyPosition = commandsHistory.length;
            } else if (e.key === 'ArrowUp') {
                if (historyPosition > 0) {
                    historyPosition--;
                    commandInput.value = commandsHistory[historyPosition];
                }
            } else if (e.key === 'ArrowDown') {
                if (historyPosition < commandsHistory.length - 1) {
                    historyPosition++;
                    commandInput.value = commandsHistory[historyPosition];
                } else if (historyPosition === commandsHistory.length - 1) {
                    historyPosition++;
                    commandInput.value = '';
                }
            }
        });

        importBtn.addEventListener('click', importConfig);
        exportBtn.addEventListener('click', exportConfig);

        // Initialize
        initializeFromCookies();
        commandInput.focus();
    </script>
</body>
</html>
    